/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.notice.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.notice.dto.MiddleMessageListSearchDTO;
import org.springblade.modules.notice.dto.MiddleMessageTemplateRemoveDTO;
import org.springblade.modules.notice.dto.MiddleMessageTemplateSaveDTO;
import org.springblade.modules.notice.entity.MiddleMessageTemplate;
import org.springblade.modules.notice.enums.ChannelType;
import org.springblade.modules.notice.enums.placeholder.VariableEnum;
import org.springblade.modules.notice.utils.VariableUtil;
import org.springblade.modules.notice.vo.*;
import org.springblade.modules.notice.enums.BusinessType;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.notice.service.IMiddleMessageTemplateService;
import org.springblade.core.boot.ctrl.BladeController;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 梯无忧_消息通知_模板表 控制器
 *
 * @author ysq
 * @since 2024-11-20
 */
@RestController
@AllArgsConstructor
@RequestMapping("sida-maintain-admin/middle/message/template")
@Api(value = "梯无忧_消息通知_模板表", tags = "梯无忧_消息通知_模板表接口")
public class MiddleMessageTemplateController extends BladeController {

	private final IMiddleMessageTemplateService middleMessageTemplateService;

	private final Environment env;

	public String getUrl() {
		return env.getProperty("message.center.url");
	}

	@GetMapping("/test-url")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "测试消息中心接口")
	private R<String> testUrl(){
		return R.data(this.getUrl());
	}

	/**
	 * 新增或修改模板配置，带id为修改，否则为新增
	 * 非000000租户在2024-11~12月的版本中，暂时不开放使用此接口
	 */
	@PostMapping("/save-and-relation")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "新增模板配置")
	public R<Long> saveTemplateConfig(@RequestBody @Valid MiddleMessageTemplateSaveDTO saveDTO) {
		return R.data(middleMessageTemplateService.saveAndRelation(saveDTO));
	}

	/**
	 * 删除模板配置，单条删除
	 * 非000000租户在2024-11~12月的版本中，暂时不开放使用此接口
	 */
	@PostMapping("/delete-by-id")
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "删除模板配置")
	public R<Boolean> removeOneById(@RequestBody MiddleMessageTemplateRemoveDTO removeDTO) {
		Long id = removeDTO.getId();
		return R.data(middleMessageTemplateService.removeAndUnbind(id));
	}

	/**
	 * 模板详情
	 * 非000000租户在2024-11~12月的版本中，暂时不开放使用此接口
	 */
	@GetMapping("/detail-by-id")
	@ApiOperationSupport(order = 40)
	@ApiOperation(value = "模板详情")
	public R<MiddleMessageTemplateDetailVO> detailById(Long id) {
		return R.data(middleMessageTemplateService.detailById(id));
	}

	/**
	 * 根据条件分页查询模板配置
	 */
	@PostMapping("/admin-tenant/list-by-condition")
	@ApiOperationSupport(order = 41)
	@ApiOperation(value = "根据条件分页查询模板配置列表")
	public R<IPage<MessageTemplateConfigListVO>> listByCondition(@RequestBody @Valid MiddleMessageListSearchDTO searchDTO) {
		return R.data(middleMessageTemplateService.listByConditionAdmin(Condition.getPage(searchDTO.getQuery()), searchDTO));
	}

	/**
	 * 获取所属业务列表
	 */
	@GetMapping("/get-business-list")
	@ApiOperationSupport(order = 43)
	@ApiOperation(value = "获取所属业务列表")
	public R<List<CommonEnumInfo>> getBusinessList() {
		return R.data(BusinessType.getSelectList());
	}

	/**
	 * 获取所属通道列表
	 */
	@GetMapping("/get-channel-list")
	@ApiOperationSupport(order = 44)
	@ApiOperation(value = "获取所属通道列表")
	public R<List<CommonEnumInfo>> getChannelList() {
		return R.data(ChannelType.getSelectList());
	}

	/**
	 * 业务-变量列表
	 */
	@GetMapping("/get-variable-list")
	@ApiOperationSupport(order = 45)
	@ApiOperation(value = "业务-变量列表")
	public R<List<CommonEnumInfo>> getVariableListByBusinessType(Integer businessType) {
		// 获取业务变量枚举类
		Class<? extends VariableEnum> variableEnumClass = BusinessType.getVariableEnumClassByCode(businessType);
		return R.data(VariableUtil.getSelectList(variableEnumClass));
	}

	/**
	 * 根据sendChannel获取账号列表
	 */
	@GetMapping("/get-account-list-by-channel")
	@ApiOperationSupport(order = 46)
	@ApiOperation(value = "根据渠道获取账号列表")
	public R<List<ChannelAccountVO>> getAccountListByChannel(Integer sendChannel) {
		String prefix = this.getUrl();
		// 发起Get请求
		String url = prefix + "/channel/account/selectBySendChannel?sendChannel=";
		// 调用服务
		String result = HttpUtil.get(url + sendChannel);
		JSONObject resultJson = JSONObject.parseObject(result);
		// 解析返回结果
		if (resultJson.get("code").equals(200)) {
			JSONArray jsonArray = resultJson.getJSONArray("data");
			List<ChannelAccountVO> resultList = JSONObject.parseArray(jsonArray.toJSONString(), ChannelAccountVO.class);
			if(new Integer(2).equals(sendChannel)){
				resultList = resultList.stream()
					.filter(f -> new Integer(1).equals(f.getClientType()) || new Integer(2).equals(f.getClientType()))
					.collect(Collectors.toList());
			}
			return R.data(resultList);
		}
        throw new ServiceException("获取列表失败");
	}

	/**
	 * 根据渠道获取模板列表
	 */
	@GetMapping("/get-models-by-channel-type")
	@ApiOperationSupport(order = 47)
	@ApiOperation(value = "获取通道id对应的模板模型列表")
	public R<List<MessageTemplateVO>> getModelsByChannelType(Long sendAccountId) {
		String prefix = this.getUrl();
		// 发起Get请求
		String url = prefix + "/message/template/listBySendAccountId?sendAccountId=";
		// 调用服务
		String result = HttpUtil.get(url + sendAccountId);
		JSONObject resultJson = JSONObject.parseObject(result);
		// 解析返回结果
		if (resultJson.get("code").equals(200)) {
			JSONArray jsonArray = resultJson.getJSONArray("data");
			List<MessageTemplateVO> resultList = JSONObject.parseArray(jsonArray.toJSONString(), MessageTemplateVO.class);
			return R.data(resultList);
		}
        throw new ServiceException("获取列表失败");
	}

	/**
	 * 000000租户
	 * 根据业务类型、账号 获取 梯无忧模板列表
	 */
	@TenantIgnore
	@GetMapping("getByBusinessTypeAndAccountId")
	@ApiOperationSupport(order = 48)
	@ApiOperation(value = "根据业务类型、账号 获取 梯无忧模板列表")
	public R<List<MiddleMessageTemplate>> getByBusinessTypeAndAccountId(Integer businessType, Long sendAccountId) {
		LambdaQueryWrapper<MiddleMessageTemplate> queryWrapper = new LambdaQueryWrapper<MiddleMessageTemplate>()
			.eq(MiddleMessageTemplate::getBusinessType, businessType)
			.eq(MiddleMessageTemplate::getSendAccountId, sendAccountId)
			.eq(BaseEntity::getIsDeleted,0);
		if (BladeConstant.ADMIN_TENANT_ID.equals(AuthUtil.getTenantId())) {
			queryWrapper.eq(MiddleMessageTemplate::getTenantId, BladeConstant.ADMIN_TENANT_ID);
		} else {
			queryWrapper.in(MiddleMessageTemplate::getTenantId, BladeConstant.ADMIN_TENANT_ID, AuthUtil.getTenantId());
		}
		return R.data(middleMessageTemplateService.list(queryWrapper));
	}

	/**
	 * 	000000租户
	 *  获取短信签名
	 */
	@GetMapping("get-sms-signature")
	@ApiOperationSupport(order = 49)
	@ApiOperation(value = "获取短信签名")
	public R<List<SmsSignVO>> getSmsSignature(@RequestParam Long sendAccountId) {
		String prefix = this.getUrl();
		// 发起Get请求
		String url = prefix + "/sms/account/querySmsSignList?sendAccountId=";
		// 调用服务
		String result = HttpUtil.get(url+sendAccountId);
		JSONObject resultJson = JSONObject.parseObject(result);
		// 解析返回结果
		if (resultJson.get("code").equals(200)) {
			JSONArray jsonArray = resultJson.getJSONArray("data");
			if(!Func.isNull(jsonArray)){
				List<SmsSignVO> resultList = JSONObject.parseArray(jsonArray.toJSONString(), SmsSignVO.class);
				return R.data(resultList);
			}
			return R.data(null);
		}
		throw new ServiceException("获取短信签名失败");
	}
}
